<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class my_oauth{
	private $CI;
	
	public function __construct(){
		$this->CI =& get_instance();
	}
	
	
	public function checkAccessToken($consumer_key, $oauth_token){
		$r = $this->CI->db->query('
					SELECT Count(*) AS num 
					FROM oauth_consumer_registry 
						INNER JOIN oauth_consumer_token ON ocr_id = oct_ocr_id_ref 
					WHERE ocr_consumer_key = \''.$consumer_key.'\' 
						AND oct_token = \''.$oauth_token.'\' 
						AND oct_token_type = \'access\'
						AND oct_timestamp > Now()  
				');
		$r = $r->row();
		
		return (intval($r->num)>0? true: false);
	}
	
	public function checkConsumerKey($consumer_key, $consumer_secret){
		$r = $this->CI->db->query('
					SELECT Count(*) AS num 
					FROM  `oauth_server_registry` 
					WHERE  `osr_consumer_key` LIKE \''.$consumer_key.'\'
						AND  `osr_consumer_secret` LIKE \''.$consumer_secret.'\'
						AND  `osr_enabled` =1
						AND  `osr_status` LIKE  \'active\'
				');
		$r = $r->row();
		
		return (intval($r->num)>0? true: false);
	}
	
	public function renewToken($oct_id, $days=3){
		$key = $this->generateKey(true);
		$this->CI->db->query('
				UPDATE oauth_consumer_token
				SET oct_token		= \''.$key.'\',
					oct_timestamp	= (Now() + INTERVAL '.Sys::$destroy_session.' DAY)
				WHERE oct_id        = '.$oct_id.'
				');
		return $key;
	}
	
	public function checkUriApp($token, $url){
		$r = $this->CI->db->query('
					SELECT cr.ocr_consumer_key, cr.ocr_consumer_secret
					FROM  `oauth_consumer_token` AS ct
					INNER JOIN oauth_consumer_registry AS cr ON cr.ocr_id = ct.oct_ocr_id_ref
					WHERE ct.oct_token =  \''.$token.'\'
		');
		$r = $r->row();
		
		$r = $this->CI->db->query('
					SELECT Count(*) AS num 
					FROM  `oauth_server_registry` 
					WHERE  osr_consumer_key =  \''.$r->ocr_consumer_key.'\'
						AND osr_consumer_secret =  \''.$r->ocr_consumer_secret.'\'
						AND`osr_status` = \'active\'
						AND  `osr_application_uri` LIKE \'%'.$url.'%\'
		');
		$r = $r->row();
		
		return (intval($r->num)>0? true: false);
	}
	
}
?>